﻿using System.Configuration;
using Accona.Monitoring.AppStatistics;
using NServiceBus;
using NServiceBus.Config;
using NServiceBus.Config.ConfigurationSource;
using NServiceBus.Unicast.Transport.Msmq;

namespace Accona.Monitoring.Publishers.nServiceBus
{
    public class nServiceBusExposure : IPublisher
    {
        private IBus Bus;

        public nServiceBusExposure()
        {
            
            Bus = NServiceBus.Configure.With()
                .CustomConfigurationSource(new MyConfigSource())
                .DefaultBuilder()
                .XmlSerializer()
                .MsmqTransport()
                    .IsTransactional(false)
                    .PurgeOnStartup(false)
                .UnicastBus()
                    .ImpersonateSender(false)
                    
                .CreateBus()

                .Start();

            
        }

        public class MyConfigSource : IConfigurationSource
        {
            public T GetConfiguration<T>() where T : class
            {
                // the part you are overriding
                if (typeof(T) == typeof(MsmqTransportConfig))
                    return new MsmqTransportConfig { InputQueue = "someQueue", /* other values */ } as T;

                // leaving the rest of the configuration as is:
                return ConfigurationManager.GetSection(typeof(T).Name) as T;
            }
        }

        public void Publish(AppStatisticsEvent appStatisticsEvent)
        {
            this.Bus.Send(new AppStatisticsServiceBusEvent()
                              {
                                  AppStatisticsEvent = appStatisticsEvent
                              });
        }
    }

    public class AppStatisticsServiceBusEvent : IMessage
    {
        public AppStatisticsEvent AppStatisticsEvent { get; set; }
    }
}
